package com.test.Utils;

import com.opencsv.CSVReader;
import com.opencsv.exceptions.CsvException;
import com.test.entity.StockTrade;

import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.nio.charset.Charset;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

public class CsvReader {
    public static int number = 0 ;
    public static List<StockTrade> readCsv(InputStream inputStream) {

        try (CSVReader reader = new CSVReader(new InputStreamReader(inputStream, Charset.forName("GBK")))) {
            List<String[]> records = reader.readAll();
            List<StockTrade> stockTrades = new ArrayList<>();

            // 定义可能的日期时间格式数组
            String[] formats = {"yyyy-MM-dd HH:mm:ss", "yyyy/MM/dd HH:mm:ss"};

            for (String[] record : records) {
                StockTrade stockTrade = new StockTrade();
                Long time = null;
                // 尝试多种格式进行解析
                for (String format : formats) {
                    try {
                        SimpleDateFormat sdf = new SimpleDateFormat(format);

                        Date date = sdf.parse(record[0]);
                        time = date.getTime();
                        if(CsvReader.number<20){
                            System.out.println(record[0]);
                            System.out.println("解析后的时间是"+time);
                            CsvReader.number++;
                        }

                        break;
                    } catch (ParseException e) {
                        // 记录每种格式解析失败的情况，方便排查问题
                    }
                }
                if (time == null) {
                    continue;
                }
                stockTrade.setTime(time);
                stockTrade.setStockCode(record[1]);
                stockTrade.setStockName(record[2]);
                stockTrade.setPrice(Double.parseDouble(record[3]));
                stockTrade.setTradeVolume(Long.parseLong(record[4]));
                stockTrade.setTradeType(record[5]);
                stockTrade.setTradePlace(record[6]);
                stockTrade.setTradePlatform(record[7]);
                stockTrade.setIndustryType(record[8]);
                stockTrades.add(stockTrade);
            }

            return stockTrades;
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        } catch (CsvException e) {
            throw new RuntimeException(e);
        }
    }
}